package com.ehsy.controller;

import com.ehsy.common.AjaxResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author YanZhen_Li
 * @version 1.0
 * @title TestController
 * @description
 * @create 2024/6/17 10:58
 */
@Controller
@ResponseBody
@RequestMapping("/test")
public class TestController {
    @RequestMapping(value = "/request/xml/body", produces = "application/xml")
    public Object requestBodyTest(
            @RequestParam(required = false) Map<String, Object> params,
            @RequestBody(required = false) Map<String, Object> body,
            HttpServletRequest request) {
        return format(params, body, request);
    }

    @RequestMapping(value = "/request/xml/body/array", produces = "application/xml")
    public Object requestBodyArrayTest(
            @RequestParam(required = false) Map<String, Object> params,
            @RequestBody(required = false) List<Object> body,
            HttpServletRequest request) {
        return format(params, body, request);
    }

    @RequestMapping(value = "/request/xml/formBody", produces = "application/xml")
    public Object requestFormBodyTest(
            @RequestParam(required = false) Map<String, Object> body,
            HttpServletRequest request) {
        return format(null, body, request);
    }

    @RequestMapping(value = "/request/xml/path/{param}", produces = "application/xml")
    public Object requestFormBodyPathTest(
            @PathVariable("param") String path,
            HttpServletRequest request) {
        return format(null, null, request);
    }

    public AjaxResult format(Map<String, Object> params, Object body, HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String value = request.getHeader(name);
            headers.put(name, value);
        }

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("headers", headers);
        result.put("method", request.getMethod());
        result.put("uri", request.getRequestURI());
        result.put("url", request.getRequestURL());
        result.put("body", body);
        result.put("params", params);
        return AjaxResult.success(result);
    }
}
